package com.itheima.utils;

import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DaoInstanceFactory {
    public static <T> T getMapper(final Class<T> interfaceClass) {  //UserDao.class
        // 动态代理

        return (T) Proxy.newProxyInstance(DaoInstanceFactory.class.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //获取连接
                SqlSession sqlSession = SqlSessionUtils.getSqlSession();
                //获取接口代理对象
                T mapper = sqlSession.getMapper(interfaceClass);
                //调用方法
                Object value = null;
                try {
                    value = method.invoke(mapper,args); // dao.findById(id);  删除选中
                    sqlSession.commit();
                } catch (Exception e) {
                    // 失败:回滚事务
                    sqlSession.rollback();
                    e.printStackTrace();
                } finally {
                    // 释放资源
                    sqlSession.close();
                }
                return value;
            }
        });
    }
}
